from flask import Blueprint, request, jsonify
from models import db, Education

education_bp = Blueprint('education', __name__)

@education_bp.route('/api/employees/<int:employee_id>/educations', methods=['GET'])
def get_educations(employee_id):
    page = int(request.args.get('page', 1))
    per_page = int(request.args.get('per_page', 10))
    query = Education.query.filter_by(employee_id=employee_id).order_by(Education.graduation_date.desc())
    pagination = query.paginate(page=page, per_page=per_page, error_out=False)
    items = [e.to_dict() for e in pagination.items]
    return jsonify({
        'data': items,
        'total': pagination.total
    })

@education_bp.route('/api/employees/<int:employee_id>/educations', methods=['POST'])
def add_education(employee_id):
    data = request.json
    edu = Education(employee_id=employee_id, **data)
    db.session.add(edu)
    db.session.commit()
    return jsonify(edu.to_dict()), 201

@education_bp.route('/api/employees/<int:employee_id>/educations/<int:education_id>', methods=['PUT'])
def update_education(employee_id, education_id):
    edu = Education.query.filter_by(id=education_id, employee_id=employee_id).first_or_404()
    for k, v in request.json.items():
        setattr(edu, k, v)
    db.session.commit()
    return jsonify(edu.to_dict())

@education_bp.route('/api/employees/<int:employee_id>/educations/<int:education_id>', methods=['DELETE'])
def delete_education(employee_id, education_id):
    edu = Education.query.filter_by(id=education_id, employee_id=employee_id).first_or_404()
    db.session.delete(edu)
    db.session.commit()
    return '', 204 